﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Broker.View.ViewModel;
using BrokerBase.Lib.Product;
using Telerik.Windows.Controls;
using System.Collections;
using BrokerBase.Lib.Company;
using BrokerBase.Lib.Query;
using Broker.View.ProductView;
using BrokerBase.Lib.Policy;
using Broker.View.Comm;
using BrokerBase.Lib.Tool;
using BrokerBase.Lib.Person;

namespace Broker.View.PolicyView
{

    /// <summary>
    /// PolicyPage.xaml 的交互逻辑
    /// </summary>
    public partial class PolicyControl : PolicyBaseControl
    {

        private ProductType pType;

        private IList<string> colRateKeys;

        private IDictionary<string, RadComboBox> cmbs = new Dictionary<string, RadComboBox>();
        //private IList<RadComboBox> cmbs = new List<RadComboBox>();

        private IPolicyLight policyLight;

        private IPolicy policy;

        private IProduct product;

        //private IPolicy original;

        private IDictionary<string, string> warnings = new Dictionary<string, string>();

        private bool isSetCmbFinish;

        //public bool IsCommit { get; set; }

        private IList<ProductNameModel> basicProductNames;

        private IList<IProduct> extraProducts;

        private SolidColorBrush darkBackgroundBrush;

        private ICompany defaultCompany;

        private RadWindow owner;

        public PolicyControl():this(null,null)
        {

        }

        public PolicyControl(IPolicyLight policyLight,RadWindow owner)
            : base(policyLight)
        {
            InitializeComponent();

            this.owner = owner;

            defaultCompany = LibGlobal.GetCurrentCompany();

            Loaded += new RoutedEventHandler(PolicyControl_Loaded);

            this.pType = policyLight.ProductType;
            
            this.policyLight = policyLight;
            
            this.policy = this.policyLight.Policy;

            if (policy.Product != null)
                colRateKeys = policy.Product.GetColRateKeys();
        }

        public PolicyControl(IPolicyLight policyLight, IProduct product, RadWindow owner)
            :this(policyLight,owner)
        {
            this.product = product;
            //cmbProduct.SelectedItem = basicProductNames.FirstOrDefault(p => p.Name == product.Name);
        }


        void PolicyControl_Loaded(object sender, RoutedEventArgs e)
        {

            darkBackgroundBrush = Application.Current.Resources["DarkBackground"] as SolidColorBrush;

            if (this.pType == ProductType.Basic)
            {
                if (defaultCompany != null && defaultCompany.Id !=0)
                {
                    basicProductNames = LibGlobal.ProductNames.Where(p => p.CompanyId == defaultCompany.Id).ToList<ProductNameModel>();
                }
                else
                {
                    basicProductNames = LibGlobal.ProductNames;
                }
                cmbProduct.ItemsSource = basicProductNames;
            }
            else
            {
                extraProducts = policy.Owner.BasicPolicy.Product.Relations.Select(p => p.Extra).ToList<IProduct>();
                cmbProduct.ItemsSource = extraProducts;
            }

            try
            {
                DataContext = policy;

                //policy.Product = this.product;

                if (this.product != null)
                {
                    SetProduct(product);
                }

                if (policy.Product != null)
                {
                    if (this.pType == ProductType.Basic)
                    {
                        cmbProduct.SelectedItem = basicProductNames.FirstOrDefault(p => p.Id == policy.Product.Id);
                        
                    }
                    else
                    {
                        cmbProduct.SelectedItem = extraProducts.FirstOrDefault(p => p.Id == policy.Product.Id);
                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace, "错误");
            }
        }

        private void SetPolicy()
        {
            policy.SettingDefault();

        }

        private void ViewPolicy()
        {
            if (policy.Product.RateType == RateType.Premium)
            {
                tblAmt.Text="保额:";
                tblAmt.Background = Brushes.White;
                tblAmt.Foreground=Brushes.Black;

            }else
            {
                tblAmt.Text="保费:";
                tblAmt.Background = Brushes.BlueViolet;
                tblAmt.Foreground=Brushes.White;
                tblAmt.ToolTip = "输入金额对应为保费";
            }

            double amt = policy.Product.RateType == RateType.Premium ? policy.Amount : policy.FixFee;
            txtImputAmount.Text = amt.ToString();

            txtImputAmount.IsEnabled = !policy.GetSettingLock("Amount");

            tblUnit.Text = policy.Product.UnitType == UnitType.Amt ? "元" : "份";

            colRateKeys = policy.Product.GetColRateKeys();
            CreateRates();

            Calc();
        }
        

        private void QueryProduct()
        {
            ListSelForm frm = new ListSelForm();
        }

        private void CreateRates()
        {
            isSetCmbFinish = false;
            cmbs.Clear();
            gridRates.Children.Clear();
            gridRates.RowDefinitions.Clear();
            //gridRates.Children.RemoveRange(0, gridRates.Children.Count);

            if (policy.Product.CanSetOverPeriod)
            {
                CreateExtraPeriodCmbs();
            }

            CreateFixRateCmbs(policy.Product.ColRateFactors);
            CreateFixRateCmbs(policy.Product.RowRateFactors);
            CreateAdjRateCmbs(policy.Product.AdjustRates);

            isSetCmbFinish = true;
        }

        private void CreateFixRateCmbs(IList<IRateFactor> rfs)
        {
            int row = gridRates.RowDefinitions.Count;

            foreach (var rf in rfs)
            {
                if (rf.IsDisplay)
                {

                    RowDefinition rowDef = new RowDefinition();
                    rowDef.Height = new GridLength(30);
                    gridRates.RowDefinitions.Add(rowDef);

                    RadComboBox cmb = CreateRateComb(rf.Name, rf, "FixRate", rf.GroupItems,null, row);

                    SetCmbDefaultValue(cmb);
                    cmbs.Add(rf.Name,cmb);
                    row++;
                }
                else
                {
                    if (rf.Axis == RateFactorAxis.Row)
                        policy.SelectedRowRateFactors[rf.Name] = rf.GetDefaultItem();
                    else
                        policy.SelectedColRateFactors[rf.Name] = rf.GetDefaultItem();
                }
            }
        }

        private void CreateAdjRateCmbs(IList<IAdjustRate> rfs)
        {
            int row = gridRates.RowDefinitions.Count;

            foreach (var rf in rfs)
            {
                RowDefinition rowDef = new RowDefinition();
                rowDef.Height = new GridLength(30);
                gridRates.RowDefinitions.Add(rowDef);

                RadComboBox cmb = CreateRateComb(rf.Name, rf, "AdjRate", rf.Items,"Name", row);
                cmbs.Add(rf.Name,cmb);
                SetCmbDefaultValue(cmb);
                row++;
            }
        }

        private void CreateExtraPeriodCmbs()
        {
            int row = gridRates.RowDefinitions.Count;

            RowDefinition rowDef = new RowDefinition();
            rowDef.Height = new GridLength(30);
            gridRates.RowDefinitions.Add(rowDef);


            int maxAge = policy.Product.MaxPayAge != null ? policy.Product.MaxPayAge.Value : policy.MaxInsuranceAge;

            int period = maxAge - policy.Owner.InsurantAge + 1;

            int[] periods = new int[period];

            for (int i = 0; i < period; i++)
            {
                periods[i] = i + 1;
            }

            RadComboBox cmb = CreateRateComb("付款/保险期限", null, "OverPeriod", periods, null, row);

            SetCmbDefaultValue(cmb);

            cmbs.Add("付款/保险期限", cmb);

        }

        private RadComboBox CreateRateComb(string name, object obj, string tag, IEnumerable items,string displayMemberPath ,int row)
        {
            TextBlock lblName = new TextBlock();
            lblName.Text = name + ":";
            lblName.Height = 24;
            lblName.SetValue(Grid.ColumnProperty, 0);
            lblName.SetValue(Grid.RowProperty, row);
            lblName.HorizontalAlignment = HorizontalAlignment.Right;
            lblName.VerticalAlignment = VerticalAlignment.Center;
            gridRates.Children.Add(lblName);

            RadComboBox cmbRate = new RadComboBox();

            cmbRate.DataContext = obj;
            cmbRate.Tag = tag;
            cmbRate.Height = 24;
            cmbRate.VerticalAlignment = VerticalAlignment.Center;
            cmbRate.ItemsSource = items;

            if(!string.IsNullOrEmpty(displayMemberPath))
                cmbRate.DisplayMemberPath = displayMemberPath;

            cmbRate.SetValue(Grid.ColumnProperty, 1);
            cmbRate.SetValue(Grid.RowProperty, row);

            gridRates.Children.Add(cmbRate);
            cmbRate.Margin = new Thickness(5, 0, 0, 0);
            //cmbRate.IsEnabled = ! policy.Owner.IsCheck;
            cmbRate.SelectionChanged += new SelectionChangedEventHandler(cmbRate_SelectionChanged);

            return cmbRate;
        }


        private void SetCmbDefaultValue(RadComboBox cmb)
        {


            if (cmb.Tag.ToString() == "FixRate")
            {
                IRateFactor rf = cmb.DataContext as IRateFactor;

                if (rf.IsHasConverter)
                {
                    cmb.SelectedItem = rf.ConverterInstance.GetItemByPolicy(policy);
                }
                else
                {
                    string s=null;

                    if (rf.Axis == RateFactorAxis.Col)
                        s = policy.SelectedColRateFactors.FirstOrDefault(p => p.Key == rf.Name).Value;
                    else if (rf.Axis == RateFactorAxis.Row)
                        s = policy.SelectedRowRateFactors.FirstOrDefault(p => p.Key == rf.Name).Value;

                    cmb.SelectedItem = s;
                }

                cmb.IsEnabled = !(policy.GetSettingLock(rf.Name) || policy.Owner.IsCheck);
            }
            else if (cmb.Tag.ToString() == "AdjRate")
            {
                IAdjustRate ar = cmb.DataContext as IAdjustRate;

                if (ar.IsHasConverter)
                {
                    IAdjustRateItem item = ar.ConverterInstance.GetItemByPolicy(policy);
                    cmb.SelectedItem = item;
                    cmb.IsEnabled = !policy.GetSettingLock(ar.Name);
                }
                else
                {
                    cmb.SelectedItem = policy.SelectedAdjRateItems.FirstOrDefault(p => p.Key == ar.Name);
                }
            }
            else if (cmb.Tag.ToString() == "OverPeriod")
            {
                cmb.SelectedItem = policy.OverPaymentPeriod;
            }
        }

        void cmbRate_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            RadComboBox cmb = sender as RadComboBox;

            if(cmb.SelectedItem==null)
                return ;

            string item=cmb.SelectedItem.ToString();
            if(cmb.Tag.ToString()=="FixRate")
            {
                IRateFactor rf = cmb.DataContext as IRateFactor;

                if (rf.Axis == RateFactorAxis.Col)
                    policy.SelectedColRateFactors[rf.Name] = item;
                else if(rf.Axis==RateFactorAxis.Row)
                    policy.SelectedRowRateFactors[rf.Name] = item;

                if (rf.IsHasConverter && rf.ConverterInstance.IsPolicySelectedEnable)
                {
                    rf.ConverterInstance.ToPolicySelected(policy,item);
                }


            }
            else if (cmb.Tag.ToString() == "AdjRate")
            {
                IAdjustRate ar = cmb.DataContext as IAdjustRate;

                IAdjustRateItem adjItem = cmb.SelectedItem as IAdjustRateItem;
                policy.SelectedAdjRateItems[ar.Name] = adjItem==null?string.Empty: adjItem.Name;
            }
            else if (cmb.Tag.ToString() == "OverPeriod")
            {
                int p=(int)cmb.SelectedItem;

                policy.OverPaymentPeriod = p;
                policy.OverInsurancePeriod = p;

            }

            Calc();
        }

        private PagingQuery BuildBasicPagingQuery()
        {
            PagingQuery pq = new PagingQuery();

            string hql = "from BasicProduct as bp where 1=1";

            if (LibGlobal.GetCurrentCompany() != null)
                hql += " and bp.Company.Id=" + LibGlobal.GetCurrentCompany().Id;


            string totalHql = "select count(*) " + hql;

            hql += " order by bp.Name";

            pq.HQL = hql;
            pq.TotalHQL = totalHql;

            return pq;
        }

        private void SetSelProductGridViewColumn(RadGridView gv)
        {
            GridViewDataColumn col1 = new GridViewDataColumn();
            col1.Header = "公司";
            col1.DataMemberBinding = new Binding("Company.Name");
            col1.Width = new GridViewLength(80, GridViewLengthUnitType.Star);
            gv.Columns.Add(col1);

            GridViewDataColumn col2 = new GridViewDataColumn();
            col2.Header = "分类";
            col2.DataMemberBinding = new Binding("Catalog");
            col2.Width = new GridViewLength(100, GridViewLengthUnitType.Star);
            gv.Columns.Add(col2);

            GridViewDataColumn col3 = new GridViewDataColumn();
            col3.Header = "名称";
            col3.DataMemberBinding = new Binding("Name");
            col3.Width = new GridViewLength(200, GridViewLengthUnitType.Star);
            gv.Columns.Add(col3);
        }


        private void AddWarning(string key,string text)
        {
            warnings[key] = text;
        }

        private void RemoveWarning(string key)
        {
            warnings.Remove(key);
        }

        private void DisplayWarning()
        {

            lstWarning.Visibility = warnings.Count > 0 ? Visibility.Visible : Visibility.Hidden;

            lstWarning.ItemsSource = warnings;
            lstWarning.Items.Refresh();
        }

        private void txtImputAmount_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter  )
            {
                Calc();
            }
        }

        private void txtImputAmount_LostFocus(object sender, RoutedEventArgs e)
        {
            Calc();
        }

        /// <summary>
        /// 验证固定费率是否已经选择完成
        /// </summary>
        /// <returns></returns>
        private bool VerifySelectFinish()
        {
            if (policy == null || policy.Product == null)
                return false;

            foreach (var cmb in cmbs)
            {
                if (cmb.Value.SelectedItem == null)
                    return false;
            }

            return true;
        }

        /// <summary>
        /// 验证固定费率选择
        /// </summary>
        /// <returns></returns>
        private bool VerifyFixRateSelected()
        {
            RatePos rp = policy.GetRatePos(colRateKeys, policy.GetColKey());

            if (rp.IsMatch)
            {
                RemoveWarning("FixRate");
                return true;
            }
            else
            {
                AddWarning("FixRate", "选择的固定费率组合无效");
                return false;
            }
        }

        private bool VerifyAmount()
        {
            double amt = 0f;

            double.TryParse(txtImputAmount.Text, out amt);
            
            
            //int amt = txtImputAmount.Text == null ? 0 : int.Parse(txtImputAmount.Value.ToString());

            if (policy.SelectedBasicAmount == null)
            {
                AddWarning("Amount", "请先选择基本保额");
                return false;
            }

            if (policy.Product.IsLadderAmount && amt >0)
            {
                int a =(int) amt;

                bool isMatch=false;


                foreach (IBasicAmount ba in policy.Product.BasicAmounts)
                {
                    if (a % ba.Basic == 0)
                    {
                        isMatch = true;
                        break;
                    }
                }

                if (isMatch)
                {
                    RemoveWarning("Amount");
                    return true;
                }
                else
                {
                    AddWarning("Amount", "输入金额必须匹配阶梯保额!");
                    return false;
                }
            }
            else if (!policy.Product.Expander.IsDecimal)
            {
                if (amt % policy.SelectedBasicAmount.Basic != 0)
                {
                    string s = tblAmt.Text;
                    AddWarning("Amount", string.Format("输入金额必须是{0}的倍数!", s));
                    return false;

                }
                else
                {
                    RemoveWarning("Amount");
                    return true;
                }
            }
            else
            {
                RemoveWarning("Amount");
                return true;
            }

            
        }
        

        /// <summary>
        /// 验证附加险的付款期限
        /// </summary>
        /// <returns></returns>
        private bool VerifyExtraPayment()
        {

            IRelation relation = policy.Product.Relations.First(p => p.Basic.Id == policy.Owner.Policies[0].Product.Id);

            if (relation.PeriodConstraint == PeriodConstraintType.Equal && policy.PaymentPeriodLength != policy.Owner.Policies[0].PaymentPeriodLength)
            {
                AddWarning("Period", "本附加险的付款期必须等于主险");
                return false;
            }

            if (relation.PeriodConstraint == PeriodConstraintType.LessOrEqual && policy.PaymentPeriodLength > policy.Owner.Policies[0].PaymentPeriodLength)
            {
                AddWarning("Period", "本附加险的付款期必须小于等于主险");
                return false;

            }

            RemoveWarning("Period");
            return true;
        }

        /// <summary>
        /// 验证保单设置是否合法
        /// </summary>
        /// <returns></returns>
        private bool VerifyCalc()
        {
            bool result = true;

            result = policy.Product !=null && isSetCmbFinish && VerifySelectFinish() && VerifyFixRateSelected() && VerifyAmount();

            if (result && policy.Product.ProductType == ProductType.Extra && !VerifyExtraPayment())
                result= false;

            return result;
        }
        /// <summary>
        /// 计算费率
        /// </summary>
        private void Calc()
        {
            try
            {
                if (VerifyCalc())
                {
                    double v = 0d;
                    double.TryParse(txtImputAmount.Text, out v);

                    if (policy.Product.RateType == RateType.Amount)
                    {
                        policy.FixFee = v;
                    }
                    else
                    {
                        policy.Amount = v;
                    }

                    bool isSuccess = PolicyUtil.SetPolicyRate(policy, LibGlobal.HbmSessionFactory.GetCurrentSession());

                    if (isSuccess)
                    {
                        RemoveWarning("RowSelected");
                        this.policy.IsVerify = true;
                        this.PolicyLight.IsVerify = true;
                        this.policyLight.FromPolicy();
                        //base.RaisePolicyChangedEvent(policy);
                    }
                    else
                    {
                        this.policy.IsVerify = false;
                        this.PolicyLight.IsVerify = false;
                        policy.Amount = 0;
                        policy.FixFee = 0;
                        AddWarning("RowSelected", string.Format("{0}与固定费率组合无效", policy.Product.RowRateFactors[0].Name));
                    }

                    //OnPolicyChanged();
                }

                if (policy.Product != null)
                {
                    DisplayWarning();
                    DisplayResult();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


        /// <summary>
        /// 显示计算结果
        /// </summary>
        private void DisplayResult()
        {
            txtAmount.Text = policy.Amount.ToString("F2");

            //tblFee.Text = "首" + policy.Product.TimeUnit.Name + "交费:";
            txtFee.Text = policy.Fee.ToString("F2");


            if (policy.OverPaymentPeriod > 1)
            {
                tblFee.Text = "首" + policy.Product.TimeUnit.Name + "交费:";
                tblFee.Background = Brushes.BlueViolet;
                tblFee.Foreground = Brushes.White;
                tblFee.ToolTip = "医疗险或者其它比较特殊的保险是一年一交的方式，每年的每年的费率随着年龄增加而不同";
            }
            else
            {
                tblFee.Background = Brushes.White;
                tblFee.Foreground = darkBackgroundBrush;
                tblFee.ToolTip = null;

                if (policy.SelectedPaymentPeriod != null)
                {
                    if (policy.SelectedPaymentPeriod.Style == PaymentPeriodStyle.Once)
                    {
                        tblFee.Text = "一次性缴费";
                    }
                    else
                    {
                        tblFee.Text = tblFee.Text = "每" + policy.Product.TimeUnit.Name + "交费:";
                    }
                }

            }

            txtTotalFee.Text = policy.TotalFee.ToString("F2");

            if (policy.SelectedPaymentPeriod != null)
                txtPaymentPeriod.Text =policy.OverPaymentPeriod>1? policy.PaymentPeriodLength+"期": policy.SelectedPaymentPeriod.Name;
            else
                txtPaymentPeriod.Text = null;
            if (policy.SelectedInsurancePeriod != null)
                txtInsurancePeriod.Text = policy.OverInsurancePeriod>1? policy.InsurancePeriodLength+"期": policy.SelectedInsurancePeriod.Name;
            else
                txtInsurancePeriod.Text = null;
        }

        private void btnView_Click(object sender, RoutedEventArgs e)
        {
            IProduct p = policy.Product;

            if (p == null)
                return;

            ProductForm frm = new ProductForm(p);

            frm.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            frm.Owner = this;

            frm.ShowDialog();
        }


        public override bool Verify()
        {
            if (policy.Product == null)
            {

                MessageBox.Show("请选择保险产品!", "提示");
                return false;
            }

            if (policy.Product.RateRows.Count > 0 && policy.Fee<=0)
            {
                MessageBox.Show("保费不能为零!请选择适当的费率组合.", "提示");
                return false;
            }

            if (!VerifyCalc())
            {
                MessageBox.Show("保单选项设置不正确!", "提示");
                return false;
            }

            return true;
        }

        private void SetProduct(IProduct product)
        {
            if (product != null)
            {
                bool initSuccess = true;
                string msg = string.Empty;

                if (policy.Product == null || policy.Product.Id != product.Id)
                {
                    policy.SelectedAdjRateItems.Clear();
                    policy.SelectedColRateFactors.Clear();
                    policy.SelectedRowRateFactors.Clear();
                    policy.SettingLockClear();

                    policy.Product = product;
                    policy.Amount = 0;
                    policy.FixFee = 0;
                    policy.MaxInsuranceAge = LibGlobal.GetClientCfg().MaxAge;
                    SetPolicy();
                }

                policy.Product.Expander.Loaded(policy);
                policy.Product.Expander.Loaded(policy, LibGlobal.HbmSessionFactory.GetCurrentSession());

                initSuccess = policy.Product.Expander.InitPolicy(policy, out msg);

                if (initSuccess)
                {
                    ViewPolicy();
                    //cmbProduct.Text = product.Name;
                    colRateKeys = product.GetColRateKeys();
                }
                else
                {
                    policy.Product = null;
                }
            }
            else
            {
                ClearData();
            }
        }

        private void cmbProduct_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                IProduct product = null;

                if (this.pType == ProductType.Basic)
                {
                    ProductNameModel pnm = cmbProduct.SelectedItem as ProductNameModel;
                    if (pnm != null)
                    {
                        product = LibGlobal.HbmSessionFactory.GetCurrentSession().Get<BasicProduct>(pnm.Id);
                    }
                }
                else
                {
                    product = cmbProduct.SelectedItem as IProduct;
                }

                SetProduct(product);

                //OnPolicyChanged();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误提示");
            }
            
        }

        public override void ClearData()
        {
            
            isSetCmbFinish = false;

            txtAmount.Text = null;
            txtFee.Text = null;
            txtFeeTu.Text = null;
            txtImputAmount.Text = null;
            txtInsurancePeriod.Text = null;
            txtPaymentPeriod.Text = null;
            txtTotalFee.Text = null;

            cmbs.Clear();
            gridRates.Children.Clear();
            gridRates.RowDefinitions.Clear();
        }

        private void cmbProduct_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            cmbProduct.IsDropDownOpen = true;
        }

        private void btnRateChoice_Click(object sender, RoutedEventArgs e)
        {
            if (this.policy != null && this.policy.Product != null)
            {
                RateColSelectForm frm = new RateColSelectForm(this.policy);

                frm.Owner = this.ParentOfType<Window>();
                frm.Width = 400;

                Point p = btnRateChoice.PointToScreen(new Point());

                frm.Left = p.X - (frm.Width / 2);
                frm.Top = p.Y+30;

                frm.ShowDialog();

                if (frm.Result != null)
                {
                    SetRateCombs(frm.Result);
                }
            }
        }

        private void SetRateCombs(IDictionary<string, string> keyCmbs)
        {
            foreach (KeyValuePair<string, string> v in keyCmbs)
            {
                RadComboBox cmb = cmbs[v.Key];

                cmb.SelectedItem = v.Value;
            }
        }

        public void OnPersonChanged(PersonType personType,IScheme scheme)
        {
            foreach (KeyValuePair<string, RadComboBox> v in cmbs)
            {
                SetCmbDefaultValue(v.Value);
            }
        }
    }
}
